using System;
using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[AddComponentMenu("")]
	[Name("Action")]
	[Description("Executes an action and returns Success or Failure. Returns Running until the action finish")]
	[Icon("Action")]
	public class BTAction : BTNodeBase, ITaskAssignable<ActionTask>, ITaskAssignable
	{
		[SerializeField]
		private UnityEngine.Object _action;

		[SerializeField]
		private BTAction _referencedNode;

		public Task task
		{
			get
			{
				return action;
			}
			set
			{
				action = (ActionTask)value;
			}
		}

		public UnityEngine.Object serializedTask
		{
			get
			{
				return _action;
			}
		}

		private ActionTask action
		{
			get
			{
				if (referencedNode != null)
				{
					return referencedNode.action;
				}
				return _action as ActionTask;
			}
			set
			{
				if (referencedNode != null)
				{
					referencedNode.action = value;
				}
				else
				{
					_action = value;
				}
				if (value != null)
				{
					value.SetOwnerSystem(base.graph);
				}
			}
		}

		public BTAction referencedNode
		{
			get
			{
				return _referencedNode;
			}
			private set
			{
				_referencedNode = value;
			}
		}

		public override string nodeName
		{
			get
			{
				return base.nodeName.ToUpper();
			}
		}

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			if (action == null)
			{
				return Status.Success;
			}
			if (base.status == Status.Resting || action.isPaused)
			{
				base.status = Status.Running;
				action.ExecuteAction(agent, blackboard, OnActionEnd);
			}
			return base.status;
		}

		private void OnActionEnd(ValueType didSucceed)
		{
			base.status = (((bool)(object)didSucceed) ? Status.Success : Status.Failure);
		}

		protected override void OnReset()
		{
			if ((bool)action)
			{
				action.EndAction(false);
			}
		}

		public override void OnGraphPaused()
		{
			if ((bool)action)
			{
				action.PauseAction();
			}
		}
	}
}
